<template>
  <div class="dashboard-container tech-page">
    <!-- 顶部统计卡片 -->
    <stat-cards :statCards="statCards" />

    <!-- 中部图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <resume-trend-chart
          :loading="loading.resumeTrend"
          :resumeTrendConfig="resumeTrendConfig"
          v-model:timeRange="timeRange"
          @change="fetchResumeCreationTrend"
        />
      </el-col>
      <el-col :span="12">
        <template-dist-chart
          :loading="loading.templateDist"
          :templateDistConfig="templateDistConfig"
        />
      </el-col>
    </el-row>

    <!-- 技能分布图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <skill-category-chart
          :loading="loading.skillCategory"
          :skillCategoryConfig="skillCategoryConfig"
        />
      </el-col>
      <el-col :span="12">
        <resume-ranking-chart
          :loading="loading.resumeRanking"
          :resumeRankingConfig="resumeRankingConfig"
        />
      </el-col>
    </el-row>

    <!-- 底部数据表格 -->
    <el-row :gutter="20" class="table-row">
      <el-col :span="24">
        <recent-resumes-table
          :loading="loading.recentResumes"
          :recentResumes="recentResumes"
        />
      </el-col>
    </el-row>

    <!-- 技能热门标签 -->
    <el-row :gutter="20" class="skill-row">
      <el-col :span="24">
        <skill-tags-cloud :loading="loading.skillTags" :skillTags="skillTags" />
      </el-col>
    </el-row>

    <!-- 数据概览仪表盘 -->
    <gauge-charts :gaugeData="gaugeData" />

    <!-- 装饰组件 -->
    <decoration-elements />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from "vue";
import StatCards from "../../components/dashboard/StatCards.vue";
import ResumeTrendChart from "../../components/dashboard/ResumeTrendChart.vue";
import TemplateDistChart from "../../components/dashboard/TemplateDistChart.vue";
import SkillCategoryChart from "../../components/dashboard/SkillCategoryChart.vue";
import ResumeRankingChart from "../../components/dashboard/ResumeRankingChart.vue";
import RecentResumesTable from "../../components/dashboard/RecentResumesTable.vue";
import SkillTagsCloud from "../../components/dashboard/SkillTagsCloud.vue";
import GaugeCharts from "../../components/dashboard/GaugeCharts.vue";
import DecorationElements from "../../components/dashboard/DecorationElements.vue";
import {
  ensureLogin,
  checkEnvironment,
  isValidEnvId,
} from "../../utils/cloudbase.js";
const cloudbaseStatus = ref({
  connected: false,
  envId: isValidEnvId ? "your-env-id" : null,
});
// export default {
//   name: 'Dashboard',
// components: {
//   StatCards,
//   ResumeTrendChart,
//   TemplateDistChart,
//   SkillCategoryChart,
//   ResumeRankingChart,
//   RecentResumesTable,
//   SkillTagsCloud,
//   GaugeCharts,
//   DecorationElements
// },
// setup() {
// 组件挂载时检查云开发状态
onMounted(async () => {
  // 检查环境配置
  const envValid = checkEnvironment();
  cloudbaseStatus.value.connected = envValid;

  if (envValid) {
    // 尝试获取登录状态
    try {
      const state = await ensureLogin();
      loginState.value = state;
    } catch (error) {
      console.warn("初始化登录状态失败:", error);
    }
  }
});
// 时间范围选择
const timeRange = ref("week");

// 加载状态
const loading = reactive({
  stats: true,
  resumeTrend: true,
  templateDist: true,
  recentResumes: true,
  skillTags: true,
  skillCategory: true,
  resumeRanking: true,
});

// 图表数据
const resumeTrendData = ref([]);
const templateDistData = ref([]);

// 统计卡片数据
const statCards = ref([
  {
    icon: "Document",
    iconClass: "icon-resume",
    value: "0",
    label: "简历总数",
  },
  {
    icon: "Files",
    iconClass: "icon-template",
    value: "0",
    label: "模板总数",
  },
  {
    icon: "Collection",
    iconClass: "icon-skill",
    value: "0",
    label: "技能总数",
  },
  {
    icon: "View",
    iconClass: "icon-view",
    value: "0",
    label: "本月访问量",
  },
]);

// 最近简历数据
const recentResumes = ref([]);

// 技能标签云数据
const skillTags = ref([]);

// 仪表盘数据
const gaugeData = ref([
  {
    title: "简历完成率",
    config: {
      data: [
        { name: "已完成", value: 80 },
        { name: "未完成", value: 20 },
      ],
      color: ["#00ffb8", "#00c0ff", "#ffe600"],
      radius: "80%",
      activeRadius: "85%",
    },
  },
  {
    title: "模板使用率",
    config: {
      data: [
        { name: "已使用", value: 65 },
        { name: "未使用", value: 35 },
      ],
      color: ["#ffe600", "#00c0ff", "#00ffb8"],
      radius: "80%",
      activeRadius: "85%",
    },
  },
  {
    title: "系统健康度",
    config: {
      data: [
        { name: "正常", value: 95 },
        { name: "异常", value: 5 },
      ],
      color: ["#00c0ff", "#ffe600", "#00ffb8"],
      radius: "80%",
      activeRadius: "85%",
    },
  },
]);

// DataV图表配置
const resumeTrendConfig = ref({
  data: [],
  colors: ["#00c0ff", "#00ffb8"],
  unit: "份",
  showValue: true,
});

const templateDistConfig = ref({
  value: 0,
  colors: ["#00c0ff", "#00ffb8"],
  borderWidth: 3,
  borderRadius: 5,
  borderGap: 3,
});

const skillCategoryConfig = ref({
  data: [30],
  shape: "rect",
  colors: ["#00c0ff", "#00ffb8"],
  waveNum: 3,
  waveHeight: 40,
  waveOpacity: 0.4,
});

const resumeRankingConfig = ref({
  data: [],
  rowNum: 5,
  waitTime: 2000,
  carousel: "single",
  unit: "份",
  sort: true,
});

// 更新仪表盘数据
const updateGaugeData = async () => {
  try {
    // 获取简历模型总数和行业模板总数，用于计算使用率
    const [resumeModelResult, industryTemplateResult] = await Promise.all([
      window.cloudbase.callFunction({
        name: "admin-resume-model-crud",
        data: {
          action: "list",
          data: { page: 1, pageSize: 1 },
        },
      }),
      window.cloudbase.callFunction({
        name: "admin-industry-resume-template-crud",
        data: {
          action: "list",
          data: { page: 1, pageSize: 1 },
        },
      }),
    ]);

    // 计算简历完成率（模拟数据，实际应该根据简历状态字段计算）
    let completedRate = 80; // 默认值
    if (
      resumeModelResult &&
      resumeModelResult.result &&
      resumeModelResult.result.data
    ) {
      // 这里假设有一个完成状态的字段，实际应根据真实数据结构调整
      const total = resumeModelResult.result.data.total || 100;
      const completed = Math.floor(total * 0.8); // 模拟80%完成率
      completedRate = Math.round((completed / total) * 100);
    }

    // 更新简历完成率
    gaugeData.value[0].config.data = [
      { name: "已完成", value: completedRate },
      { name: "未完成", value: 100 - completedRate },
    ];

    // 计算模板使用率（模拟数据，实际应该根据模板使用情况计算）
    let templateUsageRate = 65; // 默认值
    if (
      industryTemplateResult &&
      industryTemplateResult.result &&
      industryTemplateResult.result.data
    ) {
      // 这里假设有使用次数的字段，实际应根据真实数据结构调整
      const total = industryTemplateResult.result.data.total || 100;
      const used = Math.floor(total * 0.65); // 模拟65%使用率
      templateUsageRate = Math.round((used / total) * 100);
    }

    // 更新模板使用率
    gaugeData.value[1].config.data = [
      { name: "已使用", value: templateUsageRate },
      { name: "未使用", value: 100 - templateUsageRate },
    ];

    // 系统健康度（模拟数据）
    const healthRate = 95 + Math.floor(Math.random() * 5);
    gaugeData.value[2].config.data = [
      { name: "正常", value: healthRate },
      { name: "异常", value: 100 - healthRate },
    ];
  } catch (error) {
    console.error("更新仪表盘数据失败:", error);
  }
};

// 获取统计数据
const fetchStats = async () => {
  loading.stats = true;
  try {
    // 获取简历模板总数 (admin-resume-templates-crud)
    const resumeTemplatesResult = await window.cloudbase
      .callFunction({
        name: "admin-resume-templates-crud",
        data: {
          action: "list",
          data: { page: 1, pageSize: 1 },
        },
      })
      .catch(() => ({ result: { data: { total: 0 } } }));

    // 获取行业简历模板总数
    const industryTemplateResult = await window.cloudbase
      .callFunction({
        name: "admin-industry-resume-template-crud",
        data: {
          action: "list",
          data: { page: 1, pageSize: 1 },
        },
      })
      .catch(() => ({ result: { data: { total: 0 } } }));

    // 获取推荐模板总数
    const recommendTemplateResult = await window.cloudbase
      .callFunction({
        name: "admin-recommend-template-crud",
        data: {
          action: "list",
          data: { page: 1, pageSize: 1 },
        },
      })
      .catch(() => ({ result: { data: { total: 0 } } }));

    // 获取简历模型总数
    const resumeModelResult = await window.cloudbase
      .callFunction({
        name: "admin-resume-model-crud",
        data: {
          action: "list",
          data: { page: 1, pageSize: 1 },
        },
      })
      .catch(() => ({ result: { data: { total: 0 } } }));

    // 获取技能总数
    const skillsResult = await window.cloudbase
      .callFunction({
        name: "admin-skills-list-crud",
        data: {
          action: "list",
          data: { page: 1, pageSize: 1 },
        },
      })
      .catch(() => ({ result: { data: { total: 0 } } }));

    console.log("统计数据结果:", {
      resumeTemplates: resumeTemplatesResult,
      industryTemplate: industryTemplateResult,
      recommendTemplate: recommendTemplateResult,
      resumeModel: resumeModelResult,
      skills: skillsResult,
    });

    // 更新统计卡片数据
    // 简历总数 = 简历模板 + 行业简历模板 + 推荐模板 + 简历模型
    let resumeTotal = 0;
    if (
      resumeTemplatesResult &&
      resumeTemplatesResult.result &&
      resumeTemplatesResult.result.data
    ) {
      resumeTotal += resumeTemplatesResult.result.data.total || 0;
    }
    if (
      industryTemplateResult &&
      industryTemplateResult.result &&
      industryTemplateResult.result.data
    ) {
      resumeTotal += industryTemplateResult.result.data.total || 0;
    }
    if (
      recommendTemplateResult &&
      recommendTemplateResult.result &&
      recommendTemplateResult.result.data
    ) {
      resumeTotal += recommendTemplateResult.result.data.total || 0;
    }
    if (
      resumeModelResult &&
      resumeModelResult.result &&
      resumeModelResult.result.data
    ) {
      resumeTotal += resumeModelResult.result.data.total || 0;
    }
    statCards.value[0].value = resumeTotal.toLocaleString() || "0";

    // 模板总数 = 简历模型
    let templateTotal = 0;
    if (
      resumeModelResult &&
      resumeModelResult.result &&
      resumeModelResult.result.data
    ) {
      templateTotal = resumeModelResult.result.data.total || 0;
    }
    statCards.value[1].value = templateTotal.toLocaleString() || "0";

    // 技能总数
    if (skillsResult && skillsResult.result && skillsResult.result.data) {
      statCards.value[2].value = (
        skillsResult.result.data.total || 0
      ).toLocaleString();
    } else {
      statCards.value[2].value = "0";
    }

    // 本月访问量（模拟数据）
    statCards.value[3].value = Math.floor(
      Math.random() * 10000 + 5000
    ).toLocaleString();
  } catch (error) {
    console.error("获取统计数据失败:", error);
  } finally {
    loading.stats = false;
  }
};

// 获取简历创建趋势
const fetchResumeCreationTrend = async () => {
  loading.resumeTrend = true;
  try {
    // 尝试从云函数获取真实数据
    const startDate = new Date();
    const endDate = new Date();
    let dateField = "createdAt";

    if (timeRange.value === "week") {
      // 本周数据（7天）
      startDate.setDate(startDate.getDate() - 6);
    } else if (timeRange.value === "month") {
      // 本月数据（30天）
      startDate.setDate(startDate.getDate() - 29);
    } else {
      // 本年数据（12个月）
      startDate.setMonth(startDate.getMonth() - 11);
    }

    // 格式化日期为字符串
    const formatDateStr = (date) => {
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
    };

    // 尝试获取简历模型数据
    const resumeModelResult = await window.cloudbase.callFunction({
      name: "admin-resume-model-crud",
      data: {
        action: "list",
        data: {
          page: 1,
          pageSize: 1000,
          startDate: formatDateStr(startDate),
          endDate: formatDateStr(endDate),
          dateField,
        },
      },
    });

    console.log("简历趋势数据:", resumeModelResult);

    // 根据时间范围生成日期和数据
    let trendData = [];
    const now = new Date();

    // 准备日期映射
    const dateMap = {};

    if (timeRange.value === "week") {
      // 本周数据（7天）
      for (let i = 6; i >= 0; i--) {
        const date = new Date(now);
        date.setDate(date.getDate() - i);
        const dateStr = `${date.getMonth() + 1}/${date.getDate()}`;
        const fullDateStr = formatDateStr(date);
        dateMap[fullDateStr] = { name: dateStr, value: 0 };
      }
    } else if (timeRange.value === "month") {
      // 本月数据（30天，分组为10天）
      for (let i = 0; i < 3; i++) {
        const startDay = i * 10 + 1;
        const endDay = Math.min((i + 1) * 10, 30);
        const dateStr = `${startDay}-${endDay}日`;

        // 创建日期范围
        const rangeStart = new Date(now);
        rangeStart.setDate(now.getDate() - 30 + startDay);
        const rangeEnd = new Date(now);
        rangeEnd.setDate(now.getDate() - 30 + endDay);

        // 使用范围开始日期作为键
        const fullDateStr = formatDateStr(rangeStart);
        dateMap[fullDateStr] = {
          name: dateStr,
          value: 0,
          rangeStart,
          rangeEnd,
        };
      }
    } else {
      // 本年数据（12个月）
      for (let i = 0; i < 12; i++) {
        const date = new Date(now.getFullYear(), i, 1);
        const dateStr = `${i + 1}月`;
        const fullDateStr = `${date.getFullYear()}-${String(i + 1).padStart(2, "0")}`;
        dateMap[fullDateStr] = { name: dateStr, value: 0, month: i };
      }
    }

    // 如果有真实数据，处理数据
    if (
      resumeModelResult &&
      resumeModelResult.result &&
      resumeModelResult.result.data &&
      resumeModelResult.result.data.list
    ) {
      const resumeList = resumeModelResult.result.data.list;

      resumeList.forEach((resume) => {
        if (resume.createdAt) {
          const createdAt = new Date(resume.createdAt);

          if (timeRange.value === "week" || timeRange.value === "month") {
            const dateKey = formatDateStr(createdAt);

            if (timeRange.value === "week" && dateMap[dateKey]) {
              dateMap[dateKey].value++;
            } else if (timeRange.value === "month") {
              // 查找日期范围
              for (const key in dateMap) {
                const range = dateMap[key];
                if (
                  range.rangeStart &&
                  range.rangeEnd &&
                  createdAt >= range.rangeStart &&
                  createdAt <= range.rangeEnd
                ) {
                  range.value++;
                  break;
                }
              }
            }
          } else {
            // 年数据
            const monthKey = `${createdAt.getFullYear()}-${String(createdAt.getMonth() + 1).padStart(2, "0")}`;
            if (dateMap[monthKey]) {
              dateMap[monthKey].value++;
            }
          }
        }
      });
    } else {
      // 如果没有真实数据，使用模拟数据
      if (timeRange.value === "week") {
        Object.keys(dateMap).forEach((key) => {
          dateMap[key].value = Math.floor(Math.random() * 50 + 10);
        });
      } else if (timeRange.value === "month") {
        Object.keys(dateMap).forEach((key) => {
          dateMap[key].value = Math.floor(Math.random() * 150 + 50);
        });
      } else {
        Object.keys(dateMap).forEach((key) => {
          dateMap[key].value = Math.floor(Math.random() * 300 + 100);
        });
      }
    }

    // 转换为数组
    trendData = Object.values(dateMap);

    // 更新胶囊图表数据
    resumeTrendConfig.value.data = trendData;

    // 保存原始数据用于其他用途
    resumeTrendData.value = trendData;
  } catch (error) {
    console.error("获取简历创建趋势失败:", error);

    // 出错时使用模拟数据
    const now = new Date();
    let trendData = [];

    if (timeRange.value === "week") {
      for (let i = 6; i >= 0; i--) {
        const date = new Date(now);
        date.setDate(date.getDate() - i);
        const dateStr = `${date.getMonth() + 1}/${date.getDate()}`;
        const value = Math.floor(Math.random() * 50 + 10);
        trendData.push({ name: dateStr, value });
      }
    } else if (timeRange.value === "month") {
      for (let i = 0; i < 3; i++) {
        const startDay = i * 10 + 1;
        const endDay = (i + 1) * 10;
        const dateStr = `${startDay}-${endDay}日`;
        const value = Math.floor(Math.random() * 150 + 50);
        trendData.push({ name: dateStr, value });
      }
    } else {
      for (let i = 0; i < 12; i++) {
        const dateStr = `${i + 1}月`;
        const value = Math.floor(Math.random() * 300 + 100);
        trendData.push({ name: dateStr, value });
      }
    }

    resumeTrendConfig.value.data = trendData;
    resumeTrendData.value = trendData;
  } finally {
    loading.resumeTrend = false;
  }
};

// 获取模板使用分布
const fetchTemplateDistribution = async () => {
  loading.templateDist = true;
  try {
    // 获取行业简历模板列表
    const industryTemplateResult = await window.cloudbase.callFunction({
      name: "admin-industry-resume-template-crud",
      data: {
        action: "list",
        data: { page: 1, pageSize: 100 },
      },
    });

    console.log("行业模板数据:", industryTemplateResult);

    // 按标签分组统计
    const tagCounts = {};

    if (
      industryTemplateResult &&
      industryTemplateResult.result &&
      industryTemplateResult.result.data &&
      industryTemplateResult.result.data.list
    ) {
      industryTemplateResult.result.data.list.forEach((template) => {
        if (template.tags) {
          // 处理不同类型的标签数据
          let tags = [];
          if (Array.isArray(template.tags)) {
            tags = template.tags;
          } else if (typeof template.tags === "string") {
            tags = template.tags.split(",").map((tag) => tag.trim());
          }

          tags.forEach((tag) => {
            if (tag && tag.trim()) {
              const tagName = tag.trim();
              if (!tagCounts[tagName]) {
                tagCounts[tagName] = 0;
              }
              tagCounts[tagName]++;
            }
          });
        }
      });
    }

    // 获取推荐模板列表
    const recommendTemplateResult = await window.cloudbase.callFunction({
      name: "admin-recommend-template-crud",
      data: {
        action: "list",
        data: { page: 1, pageSize: 100 },
      },
    });

    console.log("推荐模板数据:", recommendTemplateResult);

    // 处理推荐模板标签
    if (
      recommendTemplateResult &&
      recommendTemplateResult.result &&
      recommendTemplateResult.result.data &&
      recommendTemplateResult.result.data.list
    ) {
      recommendTemplateResult.result.data.list.forEach((template) => {
        if (template.tags) {
          // 处理不同类型的标签数据
          let tags = [];
          if (Array.isArray(template.tags)) {
            tags = template.tags;
          } else if (typeof template.tags === "string") {
            tags = template.tags.split(",").map((tag) => tag.trim());
          }

          tags.forEach((tag) => {
            if (tag && tag.trim()) {
              const tagName = tag.trim();
              if (!tagCounts[tagName]) {
                tagCounts[tagName] = 0;
              }
              tagCounts[tagName]++;
            }
          });
        }
      });
    }

    // 如果没有标签数据，添加一些默认标签
    if (Object.keys(tagCounts).length === 0) {
      tagCounts["IT行业"] = 25;
      tagCounts["金融"] = 18;
      tagCounts["教育"] = 15;
      tagCounts["医疗"] = 12;
      tagCounts["销售"] = 10;
      tagCounts["设计"] = 8;
    }

    // 转换为图表数据格式
    const distData = Object.entries(tagCounts)
      .map(([name, value]) => ({ name, value }))
      .sort((a, b) => b.value - a.value)
      .slice(0, 6); // 只取前6个标签

    // 设置颜色
    const colors = [
      "#00c0ff",
      "#00ffb8",
      "#ffe600",
      "#ff5a5a",
      "#7a00ff",
      "#ff00d4",
      "#00ff51",
      "#ffa800",
    ];

    // 计算总数用于百分比
    const total = distData.reduce((sum, item) => sum + item.value, 0) || 1;

    // 更新百分比池图表数据
    templateDistConfig.value.value = Math.round(
      (distData[0].value / total) * 100
    );

    // 保存原始数据用于其他用途
    templateDistData.value = distData.map((item, index) => ({
      name: item.name,
      value: item.value,
      percent: Math.round((item.value / total) * 100),
      color: colors[index % colors.length],
    }));
  } catch (error) {
    console.error("获取模板使用分布失败:", error);

    // 出错时使用模拟数据
    const mockData = [
      { name: "IT行业", value: 25 },
      { name: "金融", value: 18 },
      { name: "教育", value: 15 },
      { name: "医疗", value: 12 },
      { name: "销售", value: 10 },
      { name: "设计", value: 8 },
    ];

    const colors = [
      "#00c0ff",
      "#00ffb8",
      "#ffe600",
      "#ff5a5a",
      "#7a00ff",
      "#ff00d4",
      "#00ff51",
      "#ffa800",
    ];

    const total = mockData.reduce((sum, item) => sum + item.value, 0);

    templateDistConfig.value.value = Math.round(
      (mockData[0].value / total) * 100
    );

    templateDistData.value = mockData.map((item, index) => ({
      name: item.name,
      value: item.value,
      percent: Math.round((item.value / total) * 100),
      color: colors[index % colors.length],
    }));
  } finally {
    loading.templateDist = false;
  }
};

// 获取技能分类数据
const fetchSkillCategory = async () => {
  loading.skillCategory = true;
  try {
    // 获取技能列表
    const skillsResult = await window.cloudbase.callFunction({
      name: "admin-skills-list-crud",
      data: {
        action: "list",
        data: { page: 1, pageSize: 100 },
      },
    });

    console.log("技能分类数据:", skillsResult);

    // 统计技能分类
    let totalSkills = 0;
    let categorizedSkills = 0;

    if (
      skillsResult &&
      skillsResult.result &&
      skillsResult.result.data &&
      skillsResult.result.data.list
    ) {
      totalSkills = skillsResult.result.data.list.length;

      skillsResult.result.data.list.forEach((skill) => {
        if (skill.category || skill.tag) {
          categorizedSkills++;
        }
      });
    }

    // 如果没有数据，使用模拟数据
    if (totalSkills === 0) {
      totalSkills = 100;
      categorizedSkills = 65;
    }

    // 计算分类率
    const categoryRate = Math.round((categorizedSkills / totalSkills) * 100);

    // 更新水位图数据
    skillCategoryConfig.value.data = [categoryRate];
  } catch (error) {
    console.error("获取技能分类数据失败:", error);

    // 出错时使用模拟数据
    skillCategoryConfig.value.data = [65];
  } finally {
    loading.skillCategory = false;
  }
};

// 获取简历排名数据
const fetchResumeRanking = async () => {
  loading.resumeRanking = true;
  try {
    // 获取简历模型列表
    const resumeModelResult = await window.cloudbase.callFunction({
      name: "admin-resume-model-crud",
      data: {
        action: "list",
        data: { page: 1, pageSize: 20 },
      },
    });

    console.log("简历排名数据:", resumeModelResult);

    // 处理简历数据
    let rankingData = [];

    if (
      resumeModelResult &&
      resumeModelResult.result &&
      resumeModelResult.result.data &&
      resumeModelResult.result.data.list
    ) {
      // 按创建时间排序
      const sortedResumes = [...resumeModelResult.result.data.list].sort(
        (a, b) => {
          return new Date(b.createdAt || 0) - new Date(a.createdAt || 0);
        }
      );

      // 转换为排名数据
      rankingData = sortedResumes.slice(0, 10).map((resume) => ({
        name: resume.name || "未命名简历",
        value: Math.floor(Math.random() * 100 + 10), // 模拟数据，实际应该使用真实的访问量或评分
      }));
    }

    // 如果没有数据，使用模拟数据
    if (rankingData.length === 0) {
      rankingData = [
        { name: "前端开发工程师简历", value: 96 },
        { name: "产品经理求职简历", value: 85 },
        { name: "UI设计师作品集", value: 72 },
        { name: "销售经理个人简历", value: 69 },
        { name: "软件测试工程师简历", value: 65 },
        { name: "数据分析师简历", value: 58 },
        { name: "市场营销专员简历", value: 52 },
        { name: "人力资源经理简历", value: 45 },
        { name: "财务会计简历", value: 42 },
        { name: "运营专员简历", value: 38 },
      ];
    }

    // 更新排名图表数据
    resumeRankingConfig.value.data = rankingData;
  } catch (error) {
    console.error("获取简历排名数据失败:", error);

    // 出错时使用模拟数据
    resumeRankingConfig.value.data = [
      { name: "前端开发工程师简历", value: 96 },
      { name: "产品经理求职简历", value: 85 },
      { name: "UI设计师作品集", value: 72 },
      { name: "销售经理个人简历", value: 69 },
      { name: "软件测试工程师简历", value: 65 },
      { name: "数据分析师简历", value: 58 },
      { name: "市场营销专员简历", value: 52 },
      { name: "人力资源经理简历", value: 45 },
      { name: "财务会计简历", value: 42 },
      { name: "运营专员简历", value: 38 },
    ];
  } finally {
    loading.resumeRanking = false;
  }
};

// 获取最近创建的简历
const fetchRecentResumes = async () => {
  loading.recentResumes = true;
  try {
    // 获取简历模型列表
    const resumeModelResult = await window.cloudbase.callFunction({
      name: "admin-resume-model-crud",
      data: {
        action: "list",
        data: { page: 1, pageSize: 5 },
      },
    });

    console.log("最近简历数据:", resumeModelResult);

    // 获取行业简历模板列表（用于关联模板名称）
    const industryTemplateResult = await window.cloudbase.callFunction({
      name: "admin-industry-resume-template-crud",
      data: {
        action: "list",
        data: { page: 1, pageSize: 100 },
      },
    });

    // 模板ID到名称的映射
    const templateMap = {};

    if (
      industryTemplateResult &&
      industryTemplateResult.result &&
      industryTemplateResult.result.data &&
      industryTemplateResult.result.data.list
    ) {
      industryTemplateResult.result.data.list.forEach((template) => {
        if (template._id) {
          templateMap[template._id] =
            template.name || template.title || "未命名模板";
        }
      });
    }

    // 处理简历数据
    if (
      resumeModelResult &&
      resumeModelResult.result &&
      resumeModelResult.result.data &&
      resumeModelResult.result.data.list
    ) {
      recentResumes.value = resumeModelResult.result.data.list.map((resume) => {
        return {
          _id: resume._id || "",
          title: resume.name || "未命名简历",
          username:
            resume.username ||
            "用户" +
              (resume._id
                ? resume._id.substring(0, 5)
                : Math.floor(Math.random() * 10000)),
          templateName:
            resume.templateId && templateMap[resume.templateId]
              ? templateMap[resume.templateId]
              : "自定义模板",
          createdAt: resume.createdAt || new Date().toISOString(),
        };
      });
    } else {
      // 如果没有数据，使用模拟数据
      recentResumes.value = [
        {
          _id: "mock1",
          title: "前端开发工程师简历",
          username: "张三",
          templateName: "IT行业简历模板",
          createdAt: new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString(),
        },
        {
          _id: "mock2",
          title: "产品经理求职简历",
          username: "李四",
          templateName: "互联网产品简历模板",
          createdAt: new Date(Date.now() - 1000 * 60 * 60 * 48).toISOString(),
        },
        {
          _id: "mock3",
          title: "UI设计师作品集",
          username: "王五",
          templateName: "创意设计简历模板",
          createdAt: new Date(Date.now() - 1000 * 60 * 60 * 72).toISOString(),
        },
        {
          _id: "mock4",
          title: "销售经理个人简历",
          username: "赵六",
          templateName: "商务简历模板",
          createdAt: new Date(Date.now() - 1000 * 60 * 60 * 96).toISOString(),
        },
        {
          _id: "mock5",
          title: "软件测试工程师简历",
          username: "钱七",
          templateName: "IT行业简历模板",
          createdAt: new Date(Date.now() - 1000 * 60 * 60 * 120).toISOString(),
        },
      ];
    }
  } catch (error) {
    console.error("获取最近创建的简历失败:", error);

    // 出错时使用模拟数据
    recentResumes.value = [
      {
        _id: "mock1",
        title: "前端开发工程师简历",
        username: "张三",
        templateName: "IT行业简历模板",
        createdAt: new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString(),
      },
      {
        _id: "mock2",
        title: "产品经理求职简历",
        username: "李四",
        templateName: "互联网产品简历模板",
        createdAt: new Date(Date.now() - 1000 * 60 * 60 * 48).toISOString(),
      },
      {
        _id: "mock3",
        title: "UI设计师作品集",
        username: "王五",
        templateName: "创意设计简历模板",
        createdAt: new Date(Date.now() - 1000 * 60 * 60 * 72).toISOString(),
      },
      {
        _id: "mock4",
        title: "销售经理个人简历",
        username: "赵六",
        templateName: "商务简历模板",
        createdAt: new Date(Date.now() - 1000 * 60 * 60 * 96).toISOString(),
      },
      {
        _id: "mock5",
        title: "软件测试工程师简历",
        username: "钱七",
        templateName: "IT行业简历模板",
        createdAt: new Date(Date.now() - 1000 * 60 * 60 * 120).toISOString(),
      },
    ];
  } finally {
    loading.recentResumes = false;
  }
};

// 获取技能标签
const fetchSkillTags = async () => {
  loading.skillTags = true;
  try {
    // 获取技能列表
    const skillsResult = await window.cloudbase.callFunction({
      name: "admin-skills-list-crud",
      data: {
        action: "list",
        data: { page: 1, pageSize: 100 },
      },
    });

    console.log("技能数据:", skillsResult);

    // 统计标签
    const tagCounts = {};

    if (
      skillsResult &&
      skillsResult.result &&
      skillsResult.result.data &&
      skillsResult.result.data.list
    ) {
      skillsResult.result.data.list.forEach((skill) => {
        if (skill.tag) {
          const tags = skill.tag.split(",").map((t) => t.trim());
          tags.forEach((tag) => {
            if (tag && tag.trim()) {
              if (!tagCounts[tag]) {
                tagCounts[tag] = 0;
              }
              tagCounts[tag]++;
            }
          });
        }
      });
    }

    // 如果没有标签数据，添加一些默认标签
    if (Object.keys(tagCounts).length === 0) {
      tagCounts["JavaScript"] = 15;
      tagCounts["React"] = 12;
      tagCounts["Vue"] = 10;
      tagCounts["HTML/CSS"] = 8;
      tagCounts["Node.js"] = 7;
      tagCounts["Python"] = 6;
      tagCounts["Java"] = 5;
      tagCounts["数据库"] = 4;
      tagCounts["UI设计"] = 3;
      tagCounts["产品经理"] = 3;
    }

    // 转换为标签云数据
    skillTags.value = Object.entries(tagCounts)
      .map(([name, count]) => {
        // 根据数量计算字体大小和透明度
        const size = Math.min(Math.max(count * 2 + 12, 12), 24);
        const opacity = Math.min(Math.max(count * 0.1 + 0.5, 0.5), 1);
        return { name, count, size, opacity };
      })
      .sort(() => Math.random() - 0.5); // 随机排序
  } catch (error) {
    console.error("获取技能标签失败:", error);

    // 出错时使用模拟数据
    const mockTags = [
      { name: "JavaScript", count: 15 },
      { name: "React", count: 12 },
      { name: "Vue", count: 10 },
      { name: "HTML/CSS", count: 8 },
      { name: "Node.js", count: 7 },
      { name: "Python", count: 6 },
      { name: "Java", count: 5 },
      { name: "数据库", count: 4 },
      { name: "UI设计", count: 3 },
      { name: "产品经理", count: 3 },
    ];

    skillTags.value = mockTags
      .map((tag) => {
        const size = Math.min(Math.max(tag.count * 2 + 12, 12), 24);
        const opacity = Math.min(Math.max(tag.count * 0.1 + 0.5, 0.5), 1);
        return { ...tag, size, opacity };
      })
      .sort(() => Math.random() - 0.5);
  } finally {
    loading.skillTags = false;
  }
};

// 页面加载时初始化数据
onMounted(async () => {
  await fetchStats();

  // 等待DOM更新后初始化图表
  nextTick(async () => {
    await Promise.all([
      fetchResumeCreationTrend(),
      fetchTemplateDistribution(),
      fetchRecentResumes(),
      fetchSkillTags(),
      updateGaugeData(),
      fetchSkillCategory(),
      fetchResumeRanking(),
    ]);
  });
});

//   return {
//     timeRange,
//     loading,
//     statCards,
//     recentResumes,
//     skillTags,
//     gaugeData,
//     resumeTrendData,
//     templateDistData,
//     resumeTrendConfig,
//     templateDistConfig,
//     skillCategoryConfig,
//     resumeRankingConfig,
//     fetchResumeCreationTrend
//   }
// }
// }
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  position: relative;
  overflow: hidden;
  min-height: calc(100vh - 120px);
  background-color: rgba(0, 10, 30, 0.9);
}

.chart-row,
.table-row,
.skill-row,
.gauge-row {
  margin-bottom: 20px;
}
</style>
